<template>
  <div class="raw-material-wrap">
    <!-- 条件查询区域 -->
    <el-card class="mb16">
      <el-form :model="queryForm" inline :inline-message="true">
        <el-form-item label="采购单号" prop="procureId">
          <el-input
              v-model="queryForm.procureId"
              placeholder="请输入采购单号"
              clearable
              style="width: 180px"
          />
        </el-form-item>

        <el-form-item label="商品" prop="productId">
          <el-select
              v-model="queryForm.productId"
              placeholder="请选择商品"
              clearable
              style="width: 180px"
          >
            <el-option
                v-for="p in getProOpts"
                :key="p.value"
                :label="p.label"
                :value="p.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="供应商" prop="supplierId">
          <el-select
              v-model="queryForm.supplierId"
              placeholder="请选择供应商"
              clearable
              style="width: 180px"
          >
            <el-option
                v-for="s in supplierOpts"
                :key="s.value"
                :label="s.label"
                :value="s.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="仓库" prop="warehouseId">
          <el-select
              v-model="queryForm.warehouseId"
              placeholder="请选择仓库"
              clearable
              style="width: 180px"
          >
            <el-option
                v-for="w in warehouseOpts"
                :key="w.value"
                :label="w.label"
                :value="w.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
              v-model="queryForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 180px"
          >
            <el-option label="待验收" value="1" />
            <el-option label="已入库" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row justify="space-between" align="middle" class="mb16">
      <el-button type="primary" :icon="Plus" @click="openAdd">新增入库</el-button>
      <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="size"
          v-model:current-page="page"
          @current-change="loadData"
          class="pagination"
      />
    </el-row>

    <el-table :data="tableData" stripe v-loading="loading" border>
      <el-table-column prop="materialId" label="ID" width="50" />
      <el-table-column prop="procureId" label="采购单号" width="120" />
      <el-table-column prop="productId" label="商品名称" width="90">
        <template #default="{ row }">
          {{ getProOpts.find(i => i.value === row.productId)?.label || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="num" label="数量" width="80" />
      <el-table-column prop="price" label="单价(元)" width="80" />
      <el-table-column prop="totalPrice" label="总价(元)" width="90" />
      <el-table-column prop="warehouseId" label="仓库" width="130">
        <template #default="{ row }">
          {{ warehouseOpts.find(i => i.value === row.warehouseId)?.label || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="supplierId" label="供应商" width="160">
        <template #default="{ row }">
          {{ supplierOpts.find(i => i.value === row.supplierId)?.label || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="statusColor(row.status)">
            {{ statusMap[row.status] || '未知' }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="330" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)" :disabled="row.status === 2">编辑</el-button>
          <el-popconfirm title="确定删除?" @confirm="handleDelete(row.materialId)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
          <el-button v-if="row.status === 1" size="small" type="success" @click="checkInStock(row)">验收入库</el-button>
          <el-button v-if="row.status === 1" size="small" type="primary" plain @click="showMap(row)">查看物流</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 物流路线地图弹窗 -->
    <el-dialog v-model="mapDialog" title="物流路线：供应商 → 仓库" width="80%" top="5vh" destroy-on-close @close="handleMapClose">
      <!-- 新增：里程与时长 -->
      <el-descriptions :column="2" size="mini" border class="mb12">
        <el-descriptions-item label="里程">{{ mapCarInfo.distance }} km</el-descriptions-item>
        <el-descriptions-item label="预计时长">{{ mapCarInfo.duration }} 分钟</el-descriptions-item>
      </el-descriptions>

      <Mapview :lntlat="mapLngLat" :carInfo="mapCarInfo" v-if="mapDialog" />
      <template #footer>
        <el-button @click="mapDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑抽屉 -->
    <el-drawer v-model="drawer" :title="isAdd ? '新增原材料入库' : '编辑原材料入库'" direction="rtl" size="420" destroy-on-close @closed="resetForm">
      <el-form ref="formRef" :model="form" label-width="90px" :rules="formRules">
        <el-form-item label="采购单号" prop="procureId">
          <el-select v-model="form.procureId" placeholder="请选择采购单号" clearable @change="onProcureChange">
            <el-option v-for="p in procureList" :key="p.procureId" :label="p.procureId" :value="p.procureId" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品编号"><el-input v-model="form.productId" readonly /></el-form-item>
        <el-form-item label="单价"><el-input v-model="form.price" readonly /></el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input-number v-model="form.num" :min="0.01" :precision="2" style="width:100%" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="计量单位" prop="unitId">
          <el-select v-model="form.unitId" placeholder="请选择">
            <el-option v-for="u in unitOpts" :key="u.value" :label="u.label" :value="u.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="员工" prop="employeeId">
          <el-select v-model="form.employeeId" placeholder="请选择">
            <el-option v-for="e in empOpts" :key="e.value" :label="e.label" :value="e.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择">
            <el-option v-for="w in warehouseOpts" :key="w.value" :label="w.label" :value="w.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="form.supplierId" placeholder="请选择">
            <el-option v-for="s in supplierOpts" :key="s.value" :label="s.label" :value="s.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">未审核</el-radio>
            <el-radio :label="1">待验收</el-radio>
            <el-radio :label="2">已入库</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { ElMessage, ElLoading } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Mapview from '../wms/MapContainer.vue'
import moment from 'moment'
import {
  findAll, add, update, deleteById, getUnitOpts, getEmpOpts, getWarehouseOpts,
  getSupplierOpts, getProcureMini, getProOpts, findByCondition1, update1
} from '../../api/wms.js'

const defaultForm = () => ({
  materialId: '', procureId: '', productId: '', num: 0, price: '', totalPrice: 0,
  unitId: '', employeeId: '', warehouseId: '', supplierId: '', status: 0
})

export default {
  name: 'RawMaterial',
  components: { Mapview },
  setup() { return { Plus } },
  data() {
    return {
      allData: [], loading: false, tableData: [], total: 0, page: 1, size: 6,
      drawer: false, isAdd: true, form: defaultForm(),
      formRules: {
        procureId: [{ required: true, message: '请选择采购单号', trigger: 'change' }],
        num: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        unitId: [{ required: true, message: '请选择计量单位', trigger: 'change' }],
        employeeId: [{ required: true, message: '请选择员工', trigger: 'change' }],
        warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
        supplierId: [{ required: true, message: '请选择供应商', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      unitOpts: [], empOpts: [], warehouseOpts: [], supplierOpts: [], getProOpts: [],
      statusMap: { 0: '未审核', 1: '待验收', 2: '已入库' },
      procureList: [], curProcure: null,
      warehouseLocationMap: {}, supplierLocationMap: {}, amapInstance: null, geocoder: null, driving: null,
      mapDialog: false, mapLngLat: [], mapCarInfo: {},
      queryForm: { procureId: '', productId: null, supplierId: null, warehouseId: null, status: null }
    }
  },
  mounted() {
    window._AMapSecurityConfig = { securityJsCode: '9dfc80e8bbfb6fa5ee3aa183ba8d9345' }
    this.loadProcureMini()
    this.loadSelect()
    this.loadData()
  },
  methods: {
    async loadSelect() {
      const [u, e, w, s, p] = await Promise.all([getUnitOpts(), getEmpOpts(), getWarehouseOpts(), getSupplierOpts(), getProOpts()])
      this.unitOpts = u || []; this.empOpts = e || []; this.warehouseOpts = w || []; this.supplierOpts = s || []; this.getProOpts = p || []
      this.warehouseAddrMap = Object.fromEntries(w.map(i => [i.value, i.address || '']))
      this.supplierAddrMap = Object.fromEntries(s.map(i => [i.value, i.address || '']))
      await this.initMapServices()
      await this.preparseLocations()
    },
    async initMapServices() {
      if (!this.amapInstance) {
        this.amapInstance = await (await import('@amap/amap-jsapi-loader')).load({
          key: '4d73168b715b4d45c346b0032610bc12',
          version: '2.0',
          plugins: ['AMap.Geocoder', 'AMap.Driving']
        })
      }
      if (!this.geocoder) this.geocoder = new this.amapInstance.Geocoder({ radius: 1000 })
      if (!this.driving) this.driving = new this.amapInstance.Driving({ policy: 1 })
    },
    async preparseLocations() {
      for (const it of this.warehouseOpts) {
        if (it.address && !this.warehouseLocationMap[it.value]) await this.parseLocation(it.address, this.warehouseLocationMap, it.value)
      }
      for (const it of this.supplierOpts) {
        if (it.address && !this.supplierLocationMap[it.value]) await this.parseLocation(it.address, this.supplierLocationMap, it.value)
      }
    },
    async parseLocation(addr, map, key) {
      try {
        const res = await new Promise((resolve, reject) => this.geocoder.getLocation(addr, (s, r) => s === 'complete' ? resolve(r) : reject(s)))
        if (res.geocodes?.length) map[key] = res.geocodes[0].location
      } catch (e) { console.warn('地址解析失败:', addr, e) }
    },
    async loadData() {
      this.loading = true
      try {
        this.allData = (await findByCondition1(this.queryForm))?.data?.data || []
        this.total = this.allData.length
        const start = (this.page - 1) * this.size
        this.tableData = this.allData.slice(start, start + this.size)
      } catch (e) { ElMessage.error('加载数据失败：' + e.message) } finally { this.loading = false }
    },
    statusColor(st) { return ['warning', 'success', 'primary'][st] || 'info' },
    openAdd() { this.isAdd = true; this.form = defaultForm(); this.drawer = true },
    openEdit(row) { this.isAdd = false; this.form = { ...row }; this.drawer = true },
    async handleDelete(id) { try { await deleteById(id); ElMessage.success('删除成功'); this.loadData() } catch (e) { ElMessage.error('删除失败：' + e.message) } },
    async submit() {
      await this.$refs.formRef.validate()
      this.form.totalPrice = (this.form.num * this.form.price).toFixed(2)
      await (this.isAdd ? add : update)(this.form)
      ElMessage.success(this.isAdd ? '新增成功' : '修改成功')
      this.drawer = false; this.loadData()
    },
    resetForm() { this.$refs.formRef?.resetFields(); this.form = defaultForm() },
    async loadProcureMini() { this.procureList = await getProcureMini() || [] },
    onProcureChange(val) {
      const p = this.procureList.find(i => i.procureId === val) || null
      if (p) { this.form.productId = p.productId; this.form.price = p.price; this.form.num = p.num }
      else { this.form.productId = ''; this.form.price = 0; this.form.num = 0 }
    },
    async checkInStock(row) {
      const loading = ElLoading.service({ text: '正在办理入库...' })
      try { await update1({ materialId: row.materialId, status: 2 }); ElMessage.success('验收入库成功'); this.loadData() } catch (e) { ElMessage.error('入库失败：' + (e.message || e)) } finally { loading.close() }
    },
    async showMap(row) {
      const loading = ElLoading.service({ text: '正在获取位置信息...' })
      try {
        let start = this.supplierLocationMap[row.supplierId], end = this.warehouseLocationMap[row.warehouseId]
        if (!start) { const s = this.supplierOpts.find(i => i.value === row.supplierId); if (s?.address) { await this.parseLocation(s.address, this.supplierLocationMap, row.supplierId); start = this.supplierLocationMap[row.supplierId] } }
        if (!end) { const w = this.warehouseOpts.find(i => i.value === row.warehouseId); if (w?.address) { await this.parseLocation(w.address, this.warehouseLocationMap, row.warehouseId); end = this.warehouseLocationMap[row.warehouseId] } }
        if (!start || !end) return ElMessage.error('无法获取完整位置信息')

        // 路径规划拿里程/时长
        const route = await new Promise((resolve, reject) => this.driving.search(start, end, (s, r) => s === 'complete' ? resolve(r.routes[0]) : reject(s)))
        const km = (route.distance / 1000).toFixed(1), min = Math.round(route.time / 60)

        this.mapLngLat = [start, end]
        this.mapCarInfo = {
          label: `货运-${row.procureId}`,
          parentLabel: '物流运输队',
          driver: '系统分配',
          distance: km,
          duration: min,
          rotes: {
            startTime: moment().format('YYYY-MM-DD HH:mm'),
            endTime: moment().add(min, 'minutes').format('YYYY-MM-DD HH:mm'),
            startLocation: start,
            endLocation: end
          }
        }
        this.mapDialog = true
      } catch (e) { ElMessage.error('地图数据获取失败：' + e.message) } finally { loading.close() }
    },
    handleMapClose() { this.mapLngLat = []; this.mapCarInfo = {} },
    handleQuery() { this.page = 1; this.loadData() },
    resetQuery() {
      this.queryForm = { procureId: '', productId: null, supplierId: null, warehouseId: null, status: null }
      this.page = 1; this.loadData()
    }
  }
}
</script>

<style scoped>
.raw-material-wrap { padding: 16px; min-height: 100%; }
.mb16 { margin-bottom: 16px; }
.mb12 { margin-bottom: 12px; }
::v-deep .el-table__cell { padding: 12px 0; }
::v-deep .el-dialog__body { padding: 0 !important; height: 80vh; overflow: hidden; }
</style>